$(function () {
  // 页面用到的变量
  var imgList = [];
  var page = 1; // 当前页码
  var limit = 360; // 每页显示多少条数据
  var firstAnimateCount = 360; // 第一个动画是图片张数
  var firstAnimateFlag = true; // 第一个动画是否执行
  var secondAnimateFlag = true; // 第二个动画是否执行
  var thirdAnimateFlag = true; // 第三个动画是否执行
  var lastAnimateTime = 10000;
  var saveFlag = false;
  var preFlag = false;
  var littleBoxAnimateFlag = false;
  var preTime = 10;

  var BASE_URL = "https://www.hnongyun.com";
  // var BASE_URL = "";
  var count = 0;
  var position = [];
  var pageItemList = [];
  // $(".logo-black").hide()
  function shuffleArray(array) {
    // 创建数组的浅拷贝，避免修改原始数组
    const arr = [...array];
    // Fisher-Yates 洗牌算法
    for (let i = arr.length - 1; i > 0; i--) {
      // 生成一个0到i之间的随机索引
      const j = Math.floor(Math.random() * (i + 1));
      // 交换arr[i]和arr[j]
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr;
  }
  // 获取随机区域
  function getPosition() {
    if (position.length && count < position.length) {
      // position = shuffleArray(position);
    } else {
      count = 0;
      var xCount = 5;
      var yCount = 5;
      var xOffset = 100 / xCount;
      var yOffset = 100 / yCount;
      var area = [];
      for (var i = 0; i < xCount; i++) {
        for (var j = 0; j < yCount; j++) {
          area.push({
            xMin: i * xOffset,
            xMax: (i + 1) * xOffset,
            yMin: j * yOffset,
            yMax: (j + 1) * yOffset,
          });
        }
      }
      position = [];
      for (let i = 0; i < area.length; i++) {
        var x = Math.random() * (area[i].xMax - area[i].xMin) + area[i].xMin;
        // 生成yMin, yMax之间的随机数
        var y = Math.random() * (area[i].yMax - area[i].yMin) + area[i].yMin;
        position.push([parseInt(x), parseInt(y)]);
      }
      position = shuffleArray(position);
    }

    return position[count++];
  }
  // 获取随机颜色
  function getColor() {
    try {
      // 生成随机的 RGB 值
      const r = Math.floor(Math.random() * 256);
      const g = Math.floor(Math.random() * 256);
      const b = Math.floor(Math.random() * 256);
      // 返回格式化的颜色字符串
      return `rgb(${r}, ${g}, ${b})`;
    } catch (error) {
      // 异常处理，确保函数总是返回一个有效的颜色值
      console.error("Error generating color:", error);
      return "rgb(0, 0, 0)"; // 默认返回黑色
    }
  }

  function getExt(url) {
    const arr = url.split(".");
    return arr[arr.length - 1] || "jpg";
  }

  async function preLoadImage(list) {
    var count = 0;
    while (list.length > count) {
      if (saveFlag) {
        // 获取图片后缀
        const url = list[count].image;
        const ext = getExt(url);
        saveAs(url, count + 1 + "." + ext);
      }
      if (preFlag) {
        var image = $(`<img src="${list[count].image}/>`);
        $(".img-load").append(image);
      }
      await sleep(preTime);
      count++;
    }
  }
  // 获取图片列表
  function getImageList() {
    $.ajax({
      url:
        BASE_URL +
        "/cloud-front-api/front/ows/product/api/front/ows/product/images",
      data: { page, limit },
      // dataType: "jsonp",
      success: async function (res) {
        imgList = shuffleArray(
          res.data.list.filter((item) => item.image && item.image != 1)
        );
        preLoadImage(imgList);
        // 循环图片列表，给每个图片设置随机坐标
        imgList.forEach((item) => {
          item.position = getPosition();
        });
        // 渲染图片列表
        renderImage();
      },
    });
  }

  function getImageStyle(item, autoSize = false) {
    var color = getColor();
    if (autoSize) {
      // var width = Math.
    }
    return `
      left: ${item.position[0]}%;
      top: ${item.position[1]}%;
      background-color: ${color};
      background-image: url(${item.image});
    `;
  }

  function getPageStyle(item) {
    var color = getColor();
    return `
      background-color: ${color};
      background-image: url(${item.image});
    `;
  }

  function sleep(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }

  // 第一个动画
  async function renderImage() {
    if (!firstAnimateFlag) {
      return imageAnimate2();
    }
    const data = imgList.slice(0, firstAnimateCount);
    for (let i = 0; i < data.length; i++) {
      var html = `<div class="img-item" style="${getImageStyle(
        data[i]
      )}"><div class="image-title">${data[i].name}</div></div>`;
      $("#img-container").append($(html));
      if (i > 10) {
        if (i < data.length - 1) {
          await sleep(100);
        } else {
          await imageAnimate2();
          // $("#img-container").html("");
        }
      }
    }
  }

  /**
   * 将数组按指定数量分组
   * @param {Array} array - 需要分组的数组
   * @param {number} num - 每组的元素数量
   * @returns {Array<Array>} - 分组后的二维数组
   */
  function groupArray(array, num) {
    if (!Array.isArray(array) || num <= 0) {
      throw new Error("Invalid input");
    }
    const result = [];
    for (let i = 0; i < array.length; i += num) {
      const max = array - num;
      var count = 0;
      while (array.length < num) {
        array.push(array[count]);
        count++;
        if (count >= max) {
          count = 0;
        }
      }
      var list = array.slice(i, i + num);
      if (list.length < num) {
        // TODO: 从数组末尾开始截取，取数组末尾num位
        list = array.slice(array.length - num, array.length);
      }
      result.push(list);
    }

    return result;
  }

  function getImageHtml(data) {
    return `<div class="i-box">
      <div class="i-img" style="${getPageStyle(data)}"></div>
      <div class="i-title">${data.name}</div>
    </div>`;
  }

  function renderRowItem(data) {
    var html = data.map(function (rowData) {
      const itemHtml = getImageHtml(rowData);
      return itemHtml;
    });
    return html.join("");
  }

  function renderRowFive(data, flag = littleBoxAnimateFlag) {
    const rows = groupArray(data, 5);
    const startHtmlFather =
      '<div class="grid-container bg-white overflow col-1 gap-1 p-10">';
    const endHtml = "</div>";
    const itemAnimateName = flag ? "animate2" : "animate1";
    const startHtmlSon = `<div class="full-size grid-container col-5 gap-5  page-item ${itemAnimateName}">`;
    let row = rows.map(function (item, index) {
      const rowItem = startHtmlSon + renderRowItem(item) + endHtml;
      var animateName = flag
        ? index % 2 == 1
          ? "move-left"
          : "move-right"
        : "";
      const rowItemText = `<div class="animate-container  bg-white  ${animateName} full-size">
        <div class="animate-item animate-left full-size">
          ${rowItem}
        </div>
        <div class="animate-center full-size">
          ${rowItem}
        </div>
        <div class="animate-item animate-right full-size">
          ${rowItem}
        </div>
      </div>`;
      return rowItemText;
    });
    const html = startHtmlFather + row.join("") + endHtml;
    return html;
  }

  /**
   * 将数组按指定数量分组
   * @param {Array} array - 需要分组的数组
   * @param {number} num - 每组的元素数量
   * @returns {Array<Array>} - 分组后的二维数组
   */
  function renderPage(data) {
    const page = groupArray(data, 20);
    var html = "";
    for (let i = 0; i < page.length; i++) {
      const htmlItem = renderRowFive(page[i]);
      // TODO: 添加动画
      pageItemList.push(page[i]);
      html = html + htmlItem;
    }
    return html;
  }

  function renderRowThree(data) {
    const rows = groupArray(data, 60);
    const startHtmlFather =
      '<div class="grid-container full-size overflow col-1 gap-3">';
    const endHtml = "</div>";
    const startHtmlSon =
      '<div class="full-size grid-container overflow col-3 gap-3">';
    let row = rows.map(function (item, index) {
      const pageRowItem = renderPage(item);
      const rowItem = startHtmlSon + pageRowItem + endHtml;
      var animateName = index % 2 == 0 ? "move-left-slow" : "move-right-slow";
      const rowItemText = `<div class="animate-container bg ${animateName} full-size">
        <div class="animate-item animate-left full-size">
          ${rowItem}
        </div>
        <div class="animate-center full-size">
          ${rowItem}
        </div>
        <div class="animate-item animate-right full-size">
          ${rowItem}
        </div>
      </div>`;
      return rowItemText;
    });
    const html = startHtmlFather + row.join("") + endHtml;
    return html;
  }
  function renderCenterItem(data) {
    const html = `<div class="full-size grid-container page-box  col-1 gap-1 bg-white padding-none">
      ${renderRowFive(data, true)}
    </div> `;
    $("#img-container").html(html);
  }
  // 第二个动画
  async function imageAnimate2() {
    $("#img-container").html("");
    const pageData = groupArray(imgList, 180);
    var html = "";
    var startHtml = '<div class="grid-container col-1 page-container">';
    var endHtml = "</div>";
    for (let i = 0; i < pageData.length; i++) {
      pageItemList = [];
      const htmlThree = renderRowThree(pageData[i]);
      html = html + startHtml + htmlThree + endHtml;
      $("#img-container").html(html);
      await sleep(6050);
      $(".animate-container").addClass("move-pause");

      await sleep(50);
      // $(".bg-video").hide();
      // $(".logo-white").hide()
      // $(".logo-black").show()
      renderCenterItem(pageItemList[4]);
      await sleep(4000);
      if (!secondAnimateFlag) {
        return;
      }
      // $(".bg-video").show();
      // $(".logo-white").show()
      // $(".logo-black").hide()
    }
    await renderAll();
  }

  async function renderAll() {
    if (!thirdAnimateFlag) {
      return await renderImage();
    }
    // $(".bg-video").hide();
    // $(".logo-white").hide()
    // $(".logo-black").show()
    var c = 0;
    var imgHtml = imgList.map(function (item) {
      return getImageHtml(item);
    });
    const pageNumner = 30;
    var group = groupArray(imgHtml, pageNumner);
    for (let i = 0; i < group.length; i++) {
      const row = group[i];
      var html = `<div class="last-container bg-white">
        ${row.join("")}
      </div>`;
      $("#img-container").html(html);
      await sleep(lastAnimateTime);
    }
    $("#img-container").html("");
    // $(".bg-video").show();
    // $(".logo-white").show()
    // $(".logo-black").hide()
    await renderImage();
  }
  getImageList();
});
